#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

int arr[100];

bool is_exist(int fd)
{
	for(int i=0; arr[i]; i++)
	{
		if(fd == arr[i]) return true;
	}
	return false;
}

void* strat_run(void* arg)	
{
	int clifd = *(int*)arg;
	
	char buf[1024] = {};
	while(true)
	{
		read(clifd,buf,sizeof(buf));
		printf("%s\n",buf);
		if(0 == strcmp("quit",strchr(buf, ':')+1))
		{
			close(clifd);
			pthread_exit(NULL);
		}
		for(int i=0; arr[i]; i++)
		{
			if(arr[i] != clifd)
			{
				write(arr[i],buf,strlen(buf)+1);
			}
		}
	}
}

int main()
{
	printf("服务器创建socket...\n");
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	printf("准备地址...\n");
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(7767);
	addr.sin_addr.s_addr = inet_addr("172.16.141.93");
	socklen_t len = sizeof(addr);

	printf("绑定socket与地址...\n");
	if(bind(sockfd,(struct sockaddr*)&addr,len))
	{
		perror("bind");
		return -1;
	}

	printf("设置监听...\n");
	if(listen(sockfd,5))
	{
		perror("listen");
		return -1;
	}

	int cnt = 0;

	printf("等待客户端连接...\n");
	while(true)
	{
		struct sockaddr_in addrcli = {};
		int clifd = accept(sockfd,(struct sockaddr*)&addrcli,&len);
		if(0 > clifd)
		{
			perror("accept");
			continue;
		}	
		if(!is_exist(clifd))
		{
			arr[cnt++] = clifd;
		}
		pthread_t pid;
		pthread_create(&pid, NULL, strat_run, &clifd);
	}
}
